
<!--
左滑删除组件
-->
<template>
  <div class="swipe"
       @touchstart='touchStart'
       @touchmove='touchMove'
       @touchend='touchEnd'
       :style="txtStyle"
  >
    <p>{{text}}</p>
    <a ref='remove' @click.prevent="remove()" >删除</a>
  </div>
</template>

<script>
  export default {
    data(){
      return{
        startX: 0, //触摸位置
        moveX: 0,       //滑动时的位置
        disX: 0,       //移动距离
        txtStyle: '',
        delWidth: 40,
        top: '',
        zIndex: 'z-index:-1'
      }
    },
    methods:{
      touchStart(ev) {
        ev = ev || event;
        //tounches类数组，等于1时表示此时有只有一只手指在触摸屏幕
        if (ev.touches.length == 1) {
          // 记录开始位置
          this.startX = ev.touches[0].clientX;
        }
      },
      touchMove(ev) {
        ev = ev || event;
        if(ev.touches.length == 1) {
          // 滑动过程中的实时位置
          this.moveX = ev.touches[0].clientX;
          // 滑动过程中实时计算滑动距离
          this.disX = this.startX - this.moveX;
          // console.log('disX==>',this.disX)
          // 如果是向右滑动或者只是点击，不改变滑动位置
          if(this.disX < 0 || this.disX == 0) {
            // console.log('没有移动');
            this.txtStyle = "transform:translateX(0rem)";
          }else if (this.disX > 0) {
            // 如果是向左滑动，则实时给这个根元素一个向左的偏移-left，当偏移量到达固定值delWidth时，固定元素的偏移量为 delWidth
            this.txtStyle = "transform:translateX(-" + this.disX + "px)";
            if (this.disX >= this.delWidth) {
              this.txtStyle = "transform:translateX(-" + this.delWidth + "px)";
              this.zIndex = "z-index:" + 10;
            }
          }
        }

      },
      touchEnd(ev) {
        ev = ev || event;
        if (ev.changedTouches.length == 1) {
          this.startX = 0;
          this.zIndex = "z-index:" + -1;
          // console.log(ev.changedTouches[0].clientX);
          // 手指移动结束后的水平位置
          let endX = ev.changedTouches[0].clientX;
          // 触摸开始与结束,手指移动的距离
          this.disX = this.startX - endX;
          //如果距离小于删除按钮的1/2，不显示删除按钮
        }

      },
      remove() {
        this.$emit('delIndex',this.index);
      }
    },
    props:['text','index']
  }
</script>
<style>
  .swipe {
    width: 100%;
    height: 60px;
    position: relative;
    transition: all .5s linear;
  }

  .swipe p {
    width: 100%;
    display: inline-block;
    float: left;
    height: 60px;
  }
  .swipe a {
    position: absolute;
    right: -40px;
    top: 0;
    width: 40px;
    text-align: center;
    line-height: 60px;
    height: 60px;
    display: inline-block;
    background: red;
    z-index: 100;
  }
</style>
